import {
  View,
  Button,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  useColorScheme,
  TouchableHighlight,
  Modal,
  useWindowDimensions
} from 'react-native';
import { Text, Pressable, useColorMode, useColorModeValue, useToast } from 'native-base'
import { useCallback, useContext, useEffect, useState, useRef } from 'react';
import Ionicons from 'react-native-vector-icons/Ionicons'
import appColor from '../../utils/appColor'
import ListItem from '../../components/ArticleItem';
import FadeInView from '../../components/FadeInAni';
import Request from '../../utils/Request';
import React from 'react';
import { HStack, Spinner, Heading } from 'native-base'
import { TokenContext } from '../Context'
import { ImageViewer } from 'react-native-reanimated-viewer'
import { GestureHandlerRootView, GestureDetector, Gesture, PanGestureHandler, FlatList } from 'react-native-gesture-handler'
import Animated, { useSharedValue, useAnimatedStyle, runOnJS, runOnUI, withTiming, withSequence, useDerivedValue } from 'react-native-reanimated'

const iconSize = 30
const iconColor = 'gray'



function HomeScreen({ navigation, route }) {
  const toast = useToast()
  const isDarkMode = useColorScheme() === 'dark'
  const [siteData, setSiteData] = useState([])
  const [currentSite, setCurrentSite] = useState({})
  const [currentPlate, setCurrentPlate] = useState({})
  const [currentPlateIndex, setCurrentPlateIndex] = useState(0)
  const [cardData, setCardData] = useState([])
  // const [loading, setLoading] = useState(false)
  const loading = useSharedValue(false)
  const uiLoading = useDerivedValue(() => loading.value)

  const { updateToken } = useContext(TokenContext)
  // 卡片列表ref
  const flatListRef = useRef(null);


  const fetchSite = () => {
    Request.get('/site/list').then((res) => {
      setSiteData(res.data)
      setCurrentSite(res.data[0] || '')
      setCurrentPlate(res.data[0].plates[0] || '')
    }).catch(e => {
      if (e.toString().includes('401')) {
        updateToken('')
      }
    })
  }
  const fetchList = () => {
    loading.value = true
    // 请求了列表，将列表滑动到第一条
    flatListRef.current.scrollToOffset({ offset: 0, animated: false })
    const controller = new AbortController()
    Request.get(`/content/plate/${currentSite.sid}/${currentPlate.pid}`, '', controller.signal).then(res => {
      if (res.code !== 200) {
        toast.show({ title: res.message, placement: 'top' })
      } else {
        res.data && res.data.forEach(item => {
          item.currentSid = currentSite.sid
          item.currentPid = currentPlate.pid
        })
        setCardData(res.data)
      }
      loading.value = false
    }).catch(e => {
      if (e.toString().includes('401')) {
        updateToken('')
      }
    })
    return controller
  }

  useEffect(() => {
    fetchSite()
  }, [])

  useEffect(() => {
    const control = fetchList()
    return () => control.abort()
  }, [currentPlate])


  useEffect(() => {
    if (route.params?.update) {
      // console.log('update', route.params?.update)
      navigation.setParams({ update: false })
      fetchSite()
    }
  }, [route.params?.update])


  const addSite = useCallback(() => {
    navigation.navigate('addsite')
    siteChangeVisible ? setsiteChangeVisible(false) : null
  }, [siteChangeVisible])

  // 图片全屏查看组件ref
  const imageViewerRef = useRef(null);
  const imageViewerSlide = useCallback((index) => {
    flatListRef.current.scrollToIndex({ animated: true, index, viewPosition: 0.5 })
  }, [])

  const renderCard = useCallback((props) => <ListItem {...props} viewerRef={imageViewerRef}></ListItem>, [])
  // 左右手势滑动
  const listOffsetX = useSharedValue(0)
  const listOffsetXRatio = useSharedValue(0)
  const gestureWrapStyle = useAnimatedStyle(() => {
    return {
      flex: 1,
      transform: [
        { translateX: listOffsetX.value }
      ]
    }
  }, [])
  const loadingStyle = useAnimatedStyle(() => {
    return {
      opacity: uiLoading.value ? 1 : withTiming(0),
      transform: [{
        scale: 1
      }]
    }
  }, [])
  const flatListStyle = useAnimatedStyle(() => {
    return {
      flex: 1,
      opacity: uiLoading.value ? 0 : withTiming(1),
      width: uiLoading.value ? 0 : 'auto'
    }
  }, [])
  const platePress = useCallback((plate, index) => {
    setCurrentPlateIndex(index)
    setTimeout(() => {
      loading.value = true
      setCurrentPlate(plate)
    }, 150)
  }, [])
  const winWidth = useWindowDimensions().width
  const panGestureHandle = Gesture.Pan().onBegin((e) => {

  }).onUpdate((e) => {
    // 移动列表像素
    listOffsetX.value = e.translationX
    // 移动的大小占屏幕宽度的百分比
    listOffsetXRatio.value = Math.abs(e.translationX) / winWidth
  }).onEnd((e) => {
    if (listOffsetXRatio.value > 0.17) {
      if (listOffsetX.value > 0) {
        // 右滑，选左tab
        if (currentPlateIndex) {
          let nextIndex = currentPlateIndex - 1
          runOnJS(platePress)(currentSite.plates[nextIndex], nextIndex)
          listOffsetX.value = withSequence(withTiming(winWidth, { duration: 300 }), withTiming(-winWidth, { duration: 10 }), withTiming(0, { duration: 500 }))
        } else {
          // offsetX 置0
          listOffsetX.value = withTiming(0)
        }
      } else {
        // 左滑，选右tab
        let nextIndex = currentPlateIndex + 1
        if (nextIndex < currentSite.plates.length) {
          runOnJS(platePress)(currentSite.plates[nextIndex], nextIndex)
          listOffsetX.value = withSequence(withTiming(-winWidth, { duration: 300 }), withTiming(winWidth, { duration: 10 }), withTiming(0, { duration: 500 }))
        } else {
          listOffsetX.value = withTiming(0)
        }
      }
    } else {
      listOffsetX.value = withTiming(0)
    }
    // 将offsetX的值向左或向右移动到最大值
    // 切换tab
    // offsetX 归0
  }).onFinalize((e) => {
    // console.log('final')

  })

  // const cardData = [
  //   {downUrl: 'https://sha.net/a', name: '标题提', posterImg: 'https://i01piccdn.sogoucdn.com/11df7f6e0a3aed58', tags: '测试,测试1', price: 'Free', priceTime: '2小时17分', score: '8.7', size: '1.2Gb', distribute: '8', downloads: '16', completes: '13', publisher: 'xxx'},
  //   {downUrl: 'https://sha.net/b', name: '标题提', posterImg: 'https://i01piccdn.sogoucdn.com/11df7f6e0a3aed58', tags: '测试,测试1', price: 'Free', priceTime: '2小时17分', score: '8.7', size: '1.2Gb', distribute: '8', downloads: '16', completes: '13', publisher: 'xxx'},
  //   {downUrl: 'https://sha.net/c', name: '标题提', posterImg: 'https://i01piccdn.sogoucdn.com/11df7f6e0a3aed58', tags: '测试,测试1', price: 'Free', priceTime: '2小时17分', score: '8.7', size: '1.2Gb', distribute: '8', downloads: '16', completes: '13', publisher: 'xxx'},
  //   {downUrl: 'https://sha.net/d', name: '标题提', posterImg: 'https://i01piccdn.sogoucdn.com/11df7f6e0a3aed58', tags: '测试,测试1', price: 'Free', priceTime: '2小时17分', score: '8.7', size: '1.2Gb', distribute: '8', downloads: '16', completes: '13', publisher: 'xxx'},
  //   {downUrl: 'https://sha.net/e', name: '标题提', posterImg: 'https://i01piccdn.sogoucdn.com/11df7f6e0a3aed58', tags: '测试,测试1', price: 'Free', priceTime: '2小时17分', score: '8.7', size: '1.2Gb', distribute: '8', downloads: '16', completes: '13', publisher: 'xxx'},
  // ]

  const [cSiteIcon, setcSiteIcon] = useState('chevron-down')
  const [siteChangeVisible, setsiteChangeVisible] = useState(false)

  // 下拉图标的切换
  useEffect(() => {
    siteChangeVisible ? setcSiteIcon('chevron-up') : setcSiteIcon('chevron-down')
  }, [siteChangeVisible])


  const currentSitePress = useCallback(() => setsiteChangeVisible((v) => !v), [])

  const modalPress = useCallback(() => setsiteChangeVisible((v) => !v), [])

  const siteItemPress = useCallback((site) => {
    setCurrentSite(site)
    setCurrentPlateIndex(0)
    setCurrentPlate(site.plates[0])
    setsiteChangeVisible(false)
  }, [])

  const editSite = useCallback((site) => {
    navigation.navigate({ name: 'addsite', params: site })
    siteChangeVisible ? setTimeout(_ => setsiteChangeVisible(false), 500) : null
  }, [siteChangeVisible])



  const popBg = useColorModeValue(appColor.lightPopbg, appColor.darkPopbg)
  const pageBg = useColorModeValue(appColor.lightbg, appColor.darkbg)



  return (
    <SafeAreaView style={[styles.container, { backgroundColor: pageBg }]}>
      <GestureHandlerRootView style={styles.container}>
      <View style={[styles.topView]}>
        {/* 当前站点 */}
        {currentSite ? <Pressable onPress={currentSitePress}>
          <View style={styles.topLeft}>
            <Text style={styles.topTitle}>{currentSite.siteName}</Text>
            <Ionicons name={cSiteIcon} size={22} color={iconColor}></Ionicons>
          </View>
        </Pressable>
          : <View></View>
        }
        {/* 添加站点 */}
        <View>
          <Ionicons onPress={addSite} name={'add-outline'} size={32} color={iconColor}></Ionicons>
        </View>
      </View>

      {/* 站点编辑、切换 */}
      {
        siteChangeVisible ?
          <FadeInView style={styles.FadeInView}>
            {/* shade 遮罩 */}
            <Pressable onPress={modalPress} style={styles.siteShade}>
              <View style={styles.siteWrap}>
                {
                  siteData.map(site => (
                    <TouchableHighlight key={site.siteName} onPress={() => siteItemPress(site)} activeOpacity={0.8} underlayColor={'rgba(0, 0, 0, 0)'}>
                      <View style={{ display: 'flex', borderRadius: 5, backgroundColor: popBg, flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 10, paddingVertical: 8, marginVertical: 5 }}>
                        <Text style={{ fontSize: 18, marginRight: 50 }}>{site.siteName}</Text>
                        <Ionicons onPress={() => editSite(site)} name={'create-outline'} size={22} color={iconColor}></Ionicons>
                      </View>
                    </TouchableHighlight>
                  ))
                }
              </View>
            </Pressable>

          </FadeInView>
          : null
      }

      {/* 分割线 */}
      <View style={[styles.splitLine, { backgroundColor: isDarkMode ? appColor.dark3 : appColor.light3 }]}></View>

      {/* 板块切换 */}
      <ScrollView style={{ paddingHorizontal: 10, paddingVertical: 10, height: 60, flexGrow: 0, display: 'flex', flexDirection: 'row' }} horizontal={true}>
        {
          currentSite.plates && currentSite.plates.map((plate, i) => (
            <Pressable key={i} onPress={() => platePress(plate, i)}>
              <Text style={[styles.plateItem]}>{plate.pname}</Text>
              <View style={currentPlate.pid === plate.pid ? styles.plateItemActive : null}></View>
            </Pressable>
          ))
        }
      </ScrollView>

      {
        cardData.length ?
          <ImageViewer
            ref={imageViewerRef}
            onChange={imageViewerSlide}
            data={cardData.map((el, i) => ({ key: `key-${el.posterImg}-${i}`, source: { uri: el.posterImg } }))}
          /> : null
      }


        <GestureDetector gesture={panGestureHandle}>
          <Animated.View style={gestureWrapStyle}>

            <HStack width={'100%'} space={3} position='absolute' top='1/2' justifyContent={'center'} alignItems="center">
              <Animated.View style={loadingStyle}>
                <Spinner size="lg" color={'warning.500'} />
              </Animated.View>
            </HStack>

            <Animated.View style={flatListStyle}>
              <FlatList ref={flatListRef} style={styles.scrollWrap} data={cardData} renderItem={renderCard} keyExtractor={item => item.downUrl}></FlatList>
            </Animated.View>
          </Animated.View>
        </GestureDetector>

      </GestureHandlerRootView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    // paddingTop: 5
  },
  topView: {
    flexDirection: 'row',
    paddingHorizontal: 10,
    paddingVertical: 4,
    justifyContent: 'space-between',
  },
  topLeft: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    position: 'relative',
  },
  topTitle: {
    fontSize: 22,
    marginRight: 8,
    marginLeft: 2
  },
  plateItem: {
    alignItems: 'center',
    fontSize: 20,
    paddingHorizontal: 4,
    paddingVertical: 4,
    marginHorizontal: 8
  },
  plateItemActive: {
    borderBottomColor: 'orange',
    borderBottomWidth: 3,
  },
  splitLine: {
    height: 0.7,
    marginVertical: 2,
  },
  scrollWrap: {
    paddingHorizontal: 10,
    position: 'relative',
    zIndex: 1,
  },
  FadeInView: {
    width: '100%',
    height: '100%',
    position: 'absolute',
    zIndex: 20,
    top: 45,
    backgroundColor: 'rgba(0,0,0,0)'
  },
  // 站点遮罩
  siteShade: {
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(0,0,0,0.4)'
  },
  // 站点warp
  siteWrap: {
    display: 'flex',
    flexDirection: 'column',
    paddingHorizontal: 20,
    paddingBottom: 20,
    paddingTop: 5
  }
})

export default HomeScreen